package org.pombo.sqm;

import java.util.HashMap;
import java.util.Map;

import org.pombo.gtm.InformationSet;
import org.pombo.gtm.StrategyNode;

class NodeProbabilities {

	private Map<StrategyNode, Double> probabilitiesMap;

	NodeProbabilities() {
		this.probabilitiesMap = new HashMap<StrategyNode, Double>();
	}

	double getProbability(StrategyNode node) {
		return this.probabilitiesMap.get(node).doubleValue();
	}

	void add(NodeProbabilities moreNodeProbabilities) {
		this.probabilitiesMap.putAll(moreNodeProbabilities.probabilitiesMap);
	}

	void add(StrategyNode node, double probability) {
		this.probabilitiesMap.put(node, probability);
		if (this.infoSetIsComplete(node.getInformationSet())) {
			this.normalizeInfoSet(node.getInformationSet());
		}
	}

	private boolean infoSetIsComplete(InformationSet informationSet) {
		for (StrategyNode node : informationSet.getNodes()) {
			if (!this.probabilitiesMap.containsKey(node)) {
				return false;
			}
		}
		return true;
	}

	private void normalizeInfoSet(InformationSet informationSet) {
		double total = 0;
		for (StrategyNode node : informationSet.getNodes()) {
			total += this.probabilitiesMap.get(node);
		}
		for (StrategyNode node : informationSet.getNodes()) {
			double normalizedProbability = this.probabilitiesMap.get(node) / total;
			this.probabilitiesMap.put(node, normalizedProbability);
		}
	}

}
